﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

namespace Controllers
{
    public class AuditionController : BaseController
    {
        //分页查询
        public ActionResult Find(int start, int limit, int? deptId, string name)
        {
            string idStr = deptId == null ? null : deptId.ToString();
            int empId;
            IList<int> deptIdList = getAuthedDeptIds("Audition", idStr, out empId);

            IQueryable<AuditionDTO> q = from r in ctx.AuditionMains
                                        where deptIdList.ToArray().Contains(r.DeptId)
                                        orderby r.Id descending
                                        select new AuditionDTO
                                        {
                                            Id = r.Id,
                                            Name = r.Name,
                                            Position = r.Position,
                                            Phone = r.Phone,
                                            DeptId = r.DeptId,
                                            DeptName = r.Depts.Text
                                        };
            if(!string.IsNullOrWhiteSpace(name))
            {
                q = q.Where(r => r.Name.Contains(name));
            }
            int totalCnt = q.Count();
            IList<AuditionDTO> list = q.Skip(start).Take(limit).ToList();
            foreach (var dto in list)
            {
                var subList = from r in ctx.AuditionSubs where r.Pid == dto.Id orderby r.InterviewTime descending select r;
                if (subList.Count() == 0)
                {
                    continue;
                }
                var v = subList.First();
                dto.Interviewer = v.Interviewer;
                dto.Reminder = v.Reminder;
                dto.InterviewTime = v.InterviewTime;
            }
            CJson CJson = new CJson();
            string json = CJson.ToJsonString("totalCount:" + totalCnt + ",data", list);
            return Content(json);
        }

        //删除明细
        public string DelDetail(int id)
        {
            string retStr = "Succeed";
            AuditionSub oriObj = ctx.AuditionSubs.Single(r => r.Id == id);
            ctx.AuditionSubs.DeleteOnSubmit(oriObj);
            try
            {
                ctx.SubmitChanges();
            }
            catch (Exception ex)
            {
                retStr = ex.Message;
            }
            return retStr;
        }

        //删除,含明细
        public ActionResult Delete(int id)
        {
            var rdto = new ResultMessages();
            rdto.Message = "";
            AuditionMain oriObj = ctx.AuditionMains.Single(r => r.Id == id);
            ctx.AuditionSubs.DeleteAllOnSubmit(oriObj.AuditionSubs);
            ctx.AuditionMains.DeleteOnSubmit(oriObj);
            try
            {
                ctx.SubmitChanges();
                rdto.Message = "删除成功";
                rdto.Result = true;
            }
            catch (Exception ex)
            {
                rdto.Message = ex.Message;
                rdto.Result = false;
            }
            return Json(rdto);
        }

        //事务提醒(面试)
        public ActionResult GetRemind()
        {
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            IList<string> nameList = new List<string>();
            //人资,默认提醒
            nameList.Add("王芳");
            nameList.Add("蔡建伟");
            nameList.Add("潘文亮");
            nameList.Add("朱艳华");
            //前台,默认提醒
            nameList.Add("林沛欣");
            nameList.Add("梁莹");
            nameList.Add("钟庆");
            nameList.Add("李元");
            nameList.Add("何楚虹");
            var auditionlist = (from r in ctx.AuditionSubs
                                where (r.Interviewer.Contains(ebi.Name) || r.Reminder.Contains(ebi.Name) || nameList.Contains(ebi.Name)) && r.InterviewTime >= DateTime.Now.AddMinutes(-60)
                                select new RemindDTO { Affair = "面试 " + r.AuditionMain.Position + " " + r.AuditionMain.Name, RemindTime = r.InterviewTime }).Union
                       (from r in ctx.Duties
                        where r.EmpId == ebi.Id && r.DutyDate >= DateTime.Today
                        select new RemindDTO { Affair = "值班", RemindTime = r.DutyDate }).OrderByDescending(r => r.RemindTime);
            var list = auditionlist.ToList();

            #region 考勤
            if (ebi.EmpDepPos.Where(r => r.PosId <= 4).Count() == 0)
            {
                DateTime sDate;
                DateTime eDate;
                if (DateTime.Today.Day >= 25)
                {
                    DateTime now = DateTime.Now;
                    sDate = new DateTime(now.Year, now.Month, 1);
                    eDate = new DateTime(now.Year, now.Month, DateTime.Today.Day-1);
                }
                else
                {
                    sDate = DateTime.Today.AddDays(-7);
                    eDate = DateTime.Today.AddDays(-2);
                }

                string strSql = string.Format(@"SELECT Name Affair,CardTime RemindTime
  FROM CardLog a,Employee b
  where a.JobNo=b.JobNo and b.Id={0}
	and CardTime between '{1}' and '{2}'
  order by CardTime;", ebi.Id, sDate.ToString("yyyy-MM-dd"), eDate.ToString("yyyy-MM-dd 23:59:59"));
                var cardList = ctx.ExecuteQuery<RemindDTO>(strSql).ToList();

                while (sDate <= eDate)
                {
                    if (sDate.DayOfWeek == DayOfWeek.Sunday || sDate.DayOfWeek == DayOfWeek.Saturday || (IsSpecialDate(sDate) && !IsWork(sDate)))
                    {
                        //不用上班 不做操作
                    }
                    else
                    {
                        RemindDTO sRd = cardList.FirstOrDefault(r => r.RemindTime.Day == sDate.Day);
                        if (sRd != null)
                        {
                            int sTime = int.Parse(sRd.RemindTime.ToString("yyyy-MM-dd HH:mm:ss").Substring(11, 5).Replace(":", ""));
                            #region 上班时间大于8:30
                            if (sTime > 830)
                            {
                                string record = "";
                                //读取当天的请假记录
                                string vacation = GetVacation(ebi.Id, sDate.ToString("yyyy-MM-dd 08:30:00"), "");
                                //读取当天的出差记录
                                string evection = GetEvection(ebi.Name, sDate);
                                if (vacation == "" && evection == "")
                                {
                                    if (sTime <= 900)
                                    {
                                        record = "<font color='cc0000'>" + sTime + "</font>";
                                    }
                                    else
                                    {
                                        record = "<font color='cc0000'>上午旷工</font>";
                                    }
                                    list.Insert(0, new RemindDTO { Affair = record, RemindTime = sRd.RemindTime });
                                }
                                else if (vacation != "")
                                    list.Insert(0, new RemindDTO { Affair = vacation, RemindTime = sRd.RemindTime });
                                else if (evection != "")
                                    list.Insert(0, new RemindDTO { Affair = evection, RemindTime = sRd.RemindTime });
                            }
                            #endregion

                            RemindDTO eRd = cardList.LastOrDefault(r => r.RemindTime.Day == sDate.Day);
                            int eTime = int.Parse(eRd.RemindTime.ToString("yyyy-MM-dd HH:mm:ss").Substring(11, 5).Replace(":", ""));

                            #region //下班时间早于17:30
                            if (eTime < 1730)
                            {
                                string record = "";
                                //读取当天的请假记录
                                string vacation = GetVacation(ebi.Id, sDate.ToString("yyyy-MM-dd 17:30:00"), "");
                                //读取当天的出差记录
                                string evection = GetEvection(ebi.Name, sDate);
                                if (vacation == "" && evection == "")
                                {
                                    if (eTime >= 1700)
                                    {
                                        record = "<font color='cc0000'>" + sTime + "</font>";
                                    }
                                    else
                                    {
                                        record = "<font color='cc0000'>下午旷工</font>";
                                    }
                                    list.Insert(0, new RemindDTO { Affair = record, RemindTime = eRd.RemindTime });
                                }
                                else if (vacation != "")
                                    list.Insert(0, new RemindDTO { Affair = vacation, RemindTime = eRd.RemindTime });
                                else if (evection != "")
                                    list.Insert(0, new RemindDTO { Affair = evection, RemindTime = eRd.RemindTime });
                            }
                            #endregion
                        }
                        else
                        {
                            //读取当天的请假记录
                            string vacation = GetVacation(ebi.Id, sDate.ToString("yyyy-MM-dd 08:30:00"), sDate.ToString("yyyy-MM-dd 17:30:00"));
                            //读取当天的出差记录
                            string evection = GetEvection(ebi.Name, sDate);
                            if (vacation == "" && evection == "")
                                list.Insert(0, new RemindDTO { Affair = "<font color='cc0000'>旷工</font>", RemindTime = sDate });
                        }
                    }
                    sDate = sDate.AddDays(1);
                }
            }
            #endregion

            #region 文件删除
            var fileList = from r in ctx.Files where r.OwnerId == ebi.Id && r.FileClass == 0 && r.Type != "dir" && r.CreatTime < DateTime.Today.AddMonths(-23) && r.CreatTime > DateTime.Today.AddMonths(-30) select r;
            foreach (File f in fileList)
            {
                list.Insert(0, new RemindDTO { Affair = "[快过期]" + f.Name, RemindTime = f.CreatTime.AddDays(30) });
            }
            #endregion

            return Json(list);
        }

        //根据员工ID跟日期 获取当天的请假记录情况
        private string GetVacation(int empid, string sDate, string eDate)
        {
            IEnumerable<string> vacationType;
            if (eDate == "")
            {
                vacationType = ctx.ExecuteQuery<string>(string.Format(@"SELECT a.VacationType+'|'+cast([StatusId] as nvarchar(50))FROM ReqVacationMains a,ReqVacationSubs b where a.FormNo=b.FormNo and a.EmpId={0} and '{1}' between PreStartTime and PreEndTime and a.StatusId!=0;", empid, sDate)).ToList();
            }
            else
            {
                vacationType = ctx.ExecuteQuery<string>(string.Format(@"SELECT a.VacationType+'|'+cast([StatusId] as nvarchar(50))FROM ReqVacationMains a,ReqVacationSubs b where a.FormNo=b.FormNo and a.EmpId={0} and ('{1}' between PreStartTime and PreEndTime or '{2}' between PreStartTime and PreEndTime) and a.StatusId!=0;", empid, sDate, eDate)).ToList();
                //vacationType = ctx.ExecuteQuery<string>(string.Format(@"SELECT a.VacationType+'|'+cast([StatusId] as nvarchar(50))FROM ReqVacationMains a,ReqVacationSubs b where a.FormNo=b.FormNo and a.EmpId={0} and '{1}' between PreStartTime and PreEndTime and a.StatusId!=0;", empid, eDate)).ToList();
            }
            string result = "";
            if (vacationType.Count() > 0)//有请假记录
            {
                if (vacationType.First().EndsWith("2"))
                {
                    result = "<font color='00cc00'>" + vacationType.First().Substring(0, 2) + "</font>";
                }
                else
                {
                    result = "<font color='fcd338'>" + vacationType.First().Substring(0, 2) + "审批未过</font>";
                }
            }
            return result;
        }

        //根据员工ID跟日期 获取当天的出差记录情况
        private string GetEvection(string name, DateTime sDate)
        {
            IEnumerable<string> evection = ctx.ExecuteQuery<string>(string.Format(@"SELECT cast([StatusId] as nvarchar(50))
  FROM ReqEvectionMains a,ReqEvectionSchedules b
  where a.TriperIds like '%{0}%' and a.FormNo=b.FormNo and '{1}' between PreStartTime and PreEndTime and a.StatusId!=0;", name, sDate.ToString("yyyy-MM-dd"))).ToList();
            string result = "";
            if (evection.Count() > 0)//有出差记录
            {
                if (evection.First().EndsWith("2"))
                {
                    result = "<font color='00cc00'>出差</font>";
                }
                else
                {
                    result = "<font color='fcd338'>出差审批未过</font>";
                }
            }
            return result;
        }

        private bool IsWork(DateTime date)
        {
            WorkOrRest wr = ctx.WorkOrRest.FirstOrDefault(q => q.SpecialDate.CompareTo(date) == 0);
            if (wr.IsWork == 0)
                return false;
            else
                return true;
        }

        private bool IsSpecialDate(DateTime date)
        {
            int count = ctx.WorkOrRest.Count(q => q.SpecialDate.CompareTo(date) == 0);
            if (count > 0)
                return true;
            else
                return false;
        }
    }
}